package com.android.support.lib.universal.qr.portrait;

import java.util.Collection;
import java.util.HashSet;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import com.android.support.lib.universal.R;
import com.android.support.lib.universal.qr.portrait.code.CameraManager;
import com.google.zxing.ResultPoint;

/**
 * 自定义扫描控件
 * 
 * @author 彭治铭
 *
 */
public final class ViewfinderView extends View {
	/** 动画延迟 */
	private static final long ANIMATION_DELAY = 10L;
	private static final int OPAQUE = 0xFF;// 不透明

	/**
	 * 四个蓝色边角对应的长度
	 */
	private int ScreenRate;

	/**
	 * 四个蓝色边角对应的宽度
	 */
	private static final int CORNER_WIDTH = 6;
	/**
	 * 扫描框中的中间线（移动的线） 的宽度
	 */
	private static final int MIDDLE_LINE_WIDTH = 1;

	/**
	 * 扫描框中的中间线（移动的线）的与扫描框左右的间隙
	 */
	private static final int MIDDLE_LINE_PADDING = 5;

	/**
	 * 中间那条线（移动的线）每次刷新移动的距离
	 */
	private static final int SPEEN_DISTANCE = 5;

	/**
	 * 手机的屏幕密度
	 */
	private static float density;
	/**
	 * 字体大小
	 */
	private static final int TEXT_SIZE = 16;
	/**
	 * 字体距离扫描框下面的距离
	 */
	private static final int TEXT_PADDING_TOP = 30;

	private final Paint paint;
	/** 返回的照片 */
	private Bitmap resultBitmap;
	/** 遮挡物的颜色，即除扫描框外的摄像框的遮挡物的颜色 */
	private final int maskColor;
	/** 结果颜色,扫描完了之后的背景颜色 */
	private final int resultColor;
	/** 框架颜色 */
	private int frameColor;
	/** 扫描线颜色， 扫描框中，闪动的线 */
	private final int laserColor;
	/** 结果点的颜色， 扫描框中，闪动的点 */
	private final int resultPointColor;
	/** 可能的结果点数 */
	private Collection<ResultPoint> possibleResultPoints;
	/** 最后的结果点数 */
	private Collection<ResultPoint> lastPossibleResultPoints;

	/**
	 * 中间滑动线的最顶端位置
	 */
	private int slideTop;

	/**
	 * 中间滑动线的最底端位置
	 */
	private int slideBottom;
	private boolean isFirst;

	// This constructor is used when the class is built from an XML resource.
	public ViewfinderView(Context context, AttributeSet attrs) {
		super(context, attrs);
		density = context.getResources().getDisplayMetrics().density;
		// 将像素转化成dp
		ScreenRate = (int) (25 * density);

		// Initialize these once for performance rather than calling them every
		// time in onDraw().
		paint = new Paint();
		Resources resources = getResources();
		// maskColor = resources.getColor(R.color.viewfinder_mask);
		// resultColor = resources.getColor(R.color.backgroud);
		// frameColor = Color.GREEN;//
		// resources.getColor(R.color.viewfinder_frame);
		// laserColor = resources.getColor(R.color.viewfinder_laser);
		// resultPointColor =
		// resources.getColor(R.color.possible_result_points);

		maskColor = Color.parseColor("#60000000");// 扫描外框的半透明层,扫描前
		resultColor = Color.parseColor("#b0000000");// 扫描外框的颜色，扫描后
		laserColor = Color.parseColor("#ffff0000");// 扫描框中间那根不一闪一闪的线的颜色（不是上下移动的扫描线）
		resultPointColor = Color.parseColor("#c0ffff00");// 扫描框中间那些一闪一闪的点点。

		possibleResultPoints = new HashSet<ResultPoint>(5);

	}

	@Override
	public void onDraw(Canvas canvas) {
		if (isInEditMode()) {
			return;
		}
		// 控制扫描框的大小及位置，在getFramingRect()方法中。
		Rect frame = CameraManager.get().getFramingRect();
		if (frame == null) {
			return;
		}

		if (!isFirst) {
			isFirst = true;
			slideTop = frame.top + CORNER_WIDTH;
			slideBottom = frame.bottom - CORNER_WIDTH;
		}

		int width = canvas.getWidth();
		int height = canvas.getHeight();

		// Draw the exterior (i.e. outside the framing rect) darkened
		// 画区域
		paint.setColor(resultBitmap != null ? resultColor : maskColor);
		canvas.drawRect(0, 0, width, frame.top, paint);
		canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
		if (isInEditMode()) {
			return;
		}
		canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
				paint);
		canvas.drawRect(0, frame.bottom + 1, width, height, paint);

		if (resultBitmap != null) {
			// Draw the opaque result bitmap over the scanning rectangle
			paint.setAlpha(OPAQUE);
			canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
		} else {

			frameColor = Color.parseColor("#6D6D6D");// 灰色
			paint.setColor(frameColor);
			// 画框架(四个角之间的连线)
			canvas.drawRect(frame.left, frame.top, frame.right + 1,
					frame.top + 2, paint);
			canvas.drawRect(frame.left, frame.top + 2, frame.left + 2,
					frame.bottom - 1, paint);
			canvas.drawRect(frame.right - 1, frame.top, frame.right + 1,
					frame.bottom - 1, paint);
			canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1,
					frame.bottom + 1, paint);

			frameColor = Color.parseColor("#08C8FF");// 蓝色
			paint.setColor(frameColor);//
			// 画框架上的四个角（扫描框边上的角，共8个部分）
			canvas.drawRect(frame.left - CORNER_WIDTH / 2, frame.top
					- CORNER_WIDTH / 2, frame.left + ScreenRate, frame.top
					+ CORNER_WIDTH / 2, paint);
			canvas.drawRect(frame.left - CORNER_WIDTH / 2, frame.top
					- CORNER_WIDTH / 2, frame.left + CORNER_WIDTH / 2,
					frame.top + ScreenRate, paint);
			canvas.drawRect(frame.left - CORNER_WIDTH / 2, frame.bottom
					- ScreenRate, frame.left + CORNER_WIDTH / 2, frame.bottom
					+ CORNER_WIDTH / 2, paint);
			canvas.drawRect(frame.left - CORNER_WIDTH / 2, frame.bottom
					- CORNER_WIDTH / 2, frame.left + ScreenRate, frame.bottom
					+ CORNER_WIDTH / 2, paint);
			canvas.drawRect(frame.right - ScreenRate, frame.top - CORNER_WIDTH
					/ 2, frame.right + CORNER_WIDTH / 2, frame.top
					+ CORNER_WIDTH / 2, paint);
			canvas.drawRect(frame.right - CORNER_WIDTH / 2, frame.top
					- CORNER_WIDTH / 2, frame.right + CORNER_WIDTH / 2,
					frame.top + ScreenRate, paint);
			canvas.drawRect(frame.right - CORNER_WIDTH / 2, frame.bottom
					- ScreenRate, frame.right + CORNER_WIDTH / 2, frame.bottom
					+ CORNER_WIDTH / 2, paint);
			canvas.drawRect(frame.right - ScreenRate, frame.bottom
					- CORNER_WIDTH / 2, frame.right + CORNER_WIDTH / 2,
					frame.bottom + CORNER_WIDTH / 2, paint);
			// 直接用图片 ，（扫描框里的logo图片）
			Rect bigRect = new Rect();
			bigRect.left = frame.left + 180;
			bigRect.right = frame.right - 180;
			bigRect.top = frame.top + 120;
			bigRect.bottom = frame.bottom - 120;
			Drawable drawable = getResources().getDrawable(R.drawable.lib_qr_logo);
			// 如果获取的图片是九文件。则无法强制
			BitmapDrawable b = (BitmapDrawable) drawable;
			canvas.drawBitmap(b.getBitmap(), null, bigRect, paint);

			// 自己画,画中间移动的线
			// paint.setColor(Color.GREEN);
			// canvas.drawRect(frame.left + CORNER_WIDTH, slideTop, frame.right
			// - CORNER_WIDTH, slideTop + MIDDLE_LINE_WIDTH, paint);

			// 用图片,画中间移动的线
			Rect lineRect = new Rect();
			lineRect.left = frame.left;
			lineRect.right = frame.right;
			lineRect.top = slideTop;
			lineRect.bottom = slideTop + MIDDLE_LINE_PADDING;
			canvas.drawBitmap(((BitmapDrawable) (getResources()
					.getDrawable(R.drawable.lib_qr_scan_line_blue))).getBitmap(), null,
					lineRect, paint);

			// 让线动起来，画中间移动的线
			slideTop += SPEEN_DISTANCE;
			if (slideTop >= slideBottom) {
				slideTop = frame.top + CORNER_WIDTH;
			}

			// 画扫描框下面的字
			paint.setColor(Color.WHITE);
			paint.setTextSize(TEXT_SIZE * density);
			paint.setAlpha(0x40);
			paint.setTypeface(Typeface.create("System", Typeface.BOLD));
			canvas.drawText("将二维码放入框内，即可自动扫描", frame.left, frame.bottom
					+ TEXT_PADDING_TOP * density, paint);

			Collection<ResultPoint> currentPossible = possibleResultPoints;
			Collection<ResultPoint> currentLast = lastPossibleResultPoints;

			/**
			 * 扫描框中，闪动的线
			 */
			// Draw a red "laser scanner" line through the middle to show
			// decoding is active
			// paint.setColor(laserColor);
			// paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
			// scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
			// int middle = frame.height() / 2 + frame.top;
			// canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1,
			// middle + 2, paint);

			/**
			 * 扫描框中，闪动的点
			 */
			if (currentPossible.isEmpty()) {
				lastPossibleResultPoints = null;
			} else {
				possibleResultPoints = new HashSet<ResultPoint>(5);
				lastPossibleResultPoints = currentPossible;
				paint.setAlpha(OPAQUE);
				paint.setColor(resultPointColor);
				for (ResultPoint point : currentPossible) {
					canvas.drawCircle(frame.left + point.getX(), frame.top
							+ point.getY(), 6.0f, paint);// 画扫描到的可能的点
				}
			}
			if (currentLast != null) {
				paint.setAlpha(OPAQUE / 2);
				paint.setColor(resultPointColor);
				for (ResultPoint point : currentLast) {
					canvas.drawCircle(frame.left + point.getX(), frame.top
							+ point.getY(), 3.0f, paint);
				}
			}

			// Request another update at the animation interval, but only
			// repaint the laser line,
			// not the entire viewfinder mask.
			postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
					frame.right, frame.bottom);
		}
	}

	public void drawViewfinder() {
		resultBitmap = null;
		invalidate();
	}

	/**
	 * Draw a bitmap with the result points highlighted instead of the live
	 * scanning display.
	 * 
	 * @param barcode
	 *            An image of the decoded barcode.
	 */
	public void drawResultBitmap(Bitmap barcode) {
		resultBitmap = barcode;
		invalidate();
	}

	public void addPossibleResultPoint(ResultPoint point) {
		possibleResultPoints.add(point);
	}

}
